package com.dshore.messagecenter.controller.topicqueue;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dshore.messagecenter.log.LogAnnotation;
import com.dshore.messagecenter.model.system.ResponseResult;
import com.dshore.messagecenter.service.topicQueue.ServiceAccessService;
import com.dshore.messagecenter.util.HttpUtil;
import com.dshore.messagecenter.util.UUIDUtil;

@Controller
@RequestMapping("/serviceAccess/")
public class ServiceAccessController {
	@Autowired
	private ServiceAccessService ServiceAccessService;
	@Value("${spring.send.host}")
	private String sendHost;
	/**
	 * 服务接入页面
	 * @param id 不传时为新增
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("page")
	public ModelAndView page(HttpSession session, 
			@RequestParam(value = "key",required = false) String key,
			@RequestParam(value = "id", defaultValue = "") String id,
			@RequestParam(value = "topicQueueNo", defaultValue = "",required = false) String topicQueueNo) {
		ModelAndView mv = new ModelAndView("accessType/serviceAccess");
		Map<String, Object> map=null;
		if(StringUtils.isNotBlank(key)) {
			map=(Map<String, Object>) session.getAttribute(key);
			if(map==null) {
				if(StringUtils.isNotBlank(topicQueueNo)) {
					map=ServiceAccessService.getSerivceInfo(topicQueueNo, id);
				}else {
					map = new HashMap<String, Object>();
				}
			}
		}else {
			key=UUIDUtil.getUUId();
			if(StringUtils.isNotBlank(topicQueueNo)) {
				map=ServiceAccessService.getSerivceInfo(topicQueueNo, id);
			}else {
				map = new HashMap<String, Object>();
			}
		}
		if(StringUtils.isNotBlank(id)) {
			mv.addObject("id", id);//key对应的value
		}else {
			if(map.containsKey("id")) {
				id=(String)map.get("id");
				mv.addObject("id",id);
			}else {
				mv.addObject("id","");
			}
		}
		List<Map<String,String>> targetList =null;
		if(map.containsKey("targetList")) {
			targetList = (List<Map<String, String>>) map.get("targetList");
		}else {
			targetList = new ArrayList<>();
		}
		int targetNum =  targetList.size();
		mv.addObject("targetNum", targetNum);//目标应用个数
		if(targetNum >= 1&&targetList.get(0)!=null) {
			mv.addObject("first",targetList.get(0).size());
			mv.addObject("firstApp",targetList.get(0));
			if(targetNum > 1) {
				mv.addObject("targetList", targetList.subList(1, targetList.size()));
			}
		}
		String status=null;
		if(map.containsKey("status")) {
			status=(String)map.get("status");
			mv.addObject("status",status);
		}else {
			mv.addObject("status","");
		}
		session.setAttribute(key, map);
		mv.addObject("map", map);//key对应的value
		mv.addObject("sendHost", sendHost);
		mv.addObject("key", key);//key对应的value
		return mv;
	}

	//保存主题name
	@RequestMapping(value= "saveName",method = RequestMethod.POST)
	@ResponseBody
	@SuppressWarnings("unchecked")
	public void saveOriApp(@RequestParam(value = "ServiceName",required = false) String ServiceName,
			String key,HttpSession session) {
		Map<String, Object> map = (Map<String, Object>)session.getAttribute(key);
		if(map == null) {
			map = new HashMap<>();
		}
		if(StringUtils.isNotBlank(ServiceName)) {
			map.put("ServiceName", ServiceName);
		}
		session.setAttribute(key,map);
	}
	
	
	/**
	 * 存源应用
	 */
	@RequestMapping(value= "saveOriApp",method = RequestMethod.POST)
	@ResponseBody
	@SuppressWarnings("unchecked")
	public String saveOriApp(@RequestParam(value = "originId",required = false) String originId,
						@RequestParam(value = "originName",required = false) String originName,
						String key,HttpSession session) {
		//获取session中的map
		Map<String, Object> map = (Map<String, Object>)session.getAttribute(key);
		//当session中Map有值时直接存取源应用, Map没值时创建Map存取源应用
		if(map == null) {
			map = new HashMap<>();
		}
		Map<String, String> origin=null;
		if(map.containsKey("origin")) {
			origin = (Map<String, String>) map.get("origin");
		}else {
			origin = new HashMap<>();
		}
		if(StringUtils.isNotBlank(originId)) {
			origin.put("originId", originId);
		}
		if(StringUtils.isNotBlank(originName)) {
			origin.put("originName", originName);
		}
		map.put("origin", origin);
		// 将key存到session中
		session.setAttribute(key,map);
		return key;
	}
	/**
	 * 存取模板
	 */
	@RequestMapping(value= "saveTemplate",method = RequestMethod.POST)
	@ResponseBody
	@SuppressWarnings("unchecked")
	public String saveTemplate(@RequestParam(value = "templateId",required = false) String templateId,
						@RequestParam(value = "templateName",required = false) String templateName,
						String key,HttpSession session) {
		//获取session中的map
		Map<String, Object> map = (Map<String, Object>)session.getAttribute(key);
		//当session中Map有值时直接存取源应用, Map没值时创建Map存取源应用
		if(map == null) {
			map = new HashMap<>();
		}
		Map<String, String> template=null;
		if(map.containsKey("template")) {
			template = (Map<String, String>) map.get("template");
		}else {
			template = new HashMap<>();
		}
		if(StringUtils.isNotBlank(templateId)) {
			template.put("templateId", templateId);
		}
		if(StringUtils.isNotBlank(templateName)) {
			template.put("templateName", templateName);
		}
		map.put("template", template);
		// 将key存到session中
		session.setAttribute(key,map);
		return key;
	}
	/**
	 * 去除模板
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value= "removeTemplate",method = RequestMethod.POST)
	@ResponseBody
	public void removeTemplate(String key,HttpSession session) {
		//获取session中的map
		Map<String, Object> map = (Map<String, Object>)session.getAttribute(key);
		//当session中Map有值时直接存取源应用, Map没值时创建Map存取源应用
		if(map == null) {
			map = new HashMap<>();
		}else {
			if(map.containsKey("template")) {
				map.remove("template");
			}
		}
		// 将key存到session中
		session.setAttribute(key,map);
	}
	//查询发送方式类型
	@RequestMapping("/selectBysendType")
	@ResponseBody
	public Object selectBysendType() {
		return ServiceAccessService.selectBySendType();
	}
	//新增时校验之前数据是否填写完整
	@RequestMapping(value="selectByList",method = RequestMethod.POST)
	@ResponseBody
	@SuppressWarnings("unchecked")
	public Object selectByList(int index,String key,HttpSession session) {
		Map<String, Object> map = (Map<String, Object>) session.getAttribute(key);
		List<Map<String,String>> targetList = null;
		if(map!=null) {
			if(map.containsKey("targetList")) {
				targetList = (List<Map<String,String>>) map.get("targetList");
			}else {
				targetList=new ArrayList<>();
			}
			if(targetList!=null&&targetList.size()>0) {
				if(targetList.size()>=index-1) {
					if(targetList.get(index-2).size()>=5) {
						return true;
					}
				}
			}
		}
		return false;
	}
	//修改时查看发送配置信息
	@RequestMapping(value="/selectBysend",method = RequestMethod.POST)
	@ResponseBody
	@SuppressWarnings("unchecked")
	public Map<String, String> selectBysend(int index,String key,HttpSession session) {
		Map<String, Object> map = (Map<String, Object>) session.getAttribute(key);
		//目标文件集合
		List<Map<String,String>> targetList = null;
		//map有对象时才插入
		if(map == null) {
			return null;
		} else {
			if(map.containsKey("targetList")) {
				targetList = (List<Map<String,String>>) map.get("targetList");
			}else {
				targetList=new ArrayList<>();
			}
			if(targetList == null || targetList.size()==0) {
				return null;
			}else {
				Map<String,String> target = new HashMap<>();
				if(targetList.size()>=index) {
					target=(Map<String, String>)targetList.get(index-1);
					if(target==null) {
						return null;
					}else {
						return target;
					}
				}else {
					return null;
				}
			}
		}
	}
/**
 * 存储发送配置信息
 */
@SuppressWarnings("unchecked")
@RequestMapping(value= "saveSend",method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> saveSend(String sendType,String sendConfig,String sendChannel,int index,String sendName,
		String key,HttpSession session) {
		//Session中map
		Map<String, Object> map = (Map<String, Object>) session.getAttribute(key);
		System.out.println("存储发送配置信息: " + map);
		
		//目标文件集合
		List<Map<String,String>> targetList = null;
		Map<String, String> target = null;
		//map有对象时才插入
		if(map == null) {
			map = new HashMap<>();
			targetList = new ArrayList<>();
			target=new HashMap<>();
			targetList.add(target);
		} else {
			if(map.containsKey("targetList")) {
				targetList = (List<Map<String,String>>) map.get("targetList");
			}else {
				targetList=new ArrayList<>();
			}
			//如果session中targetList为null,再创建个list
			if(targetList.size()>=index) {
				target=(Map<String,String>) targetList.get(index-1);
			}else {
				target=new HashMap<>();
				targetList.add(target);
			}
		}
		if(StringUtils.isNotBlank(sendConfig)) {
			target.put("sendConfig", sendConfig);
		}
		if(StringUtils.isNotBlank(sendType)) {
			target.put("sendType", sendType);
		}
		if(StringUtils.isNotBlank(sendChannel)) {
			target.put("sendChannel", sendChannel);
		}
		if(StringUtils.isNotBlank(sendName)) {
			target.put("sendName", sendName);
		}
		target.put("status", "1");
		map.put("targetList", targetList);
		//将map再更新存入Session中
		session.setAttribute(key, map);
		return map;
	}

	/**
	 * 存储目标应用
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value= "saveTargetApp",method = RequestMethod.POST)
	@ResponseBody
	public Object saveTargetApp(String targetId,String targetName,int index,
			String key,HttpSession session) {
		//Session中map
		Map<String, Object> map = (Map<String, Object>) session.getAttribute(key);
		//目标文件集合
		List<Map<String,String>> targetList = null;
		Map<String, String> target = new HashMap<>();
		//map有对象时才插入
		if(map == null) {
			map = new HashMap<>();
			targetList = new ArrayList<>();
			targetList.add(target);
		} else {
			if(map.containsKey("targetList")) {
				targetList = (List<Map<String,String>>) map.get("targetList");
			}else {
				targetList=new ArrayList<>();
			}
			if(targetList.size()>0) {
				for(int i=0;i<targetList.size();i++) {
					if(targetList.get(i).get("targetId")!=null&&
							targetList.get(i).get("targetId").equals(targetId)) {
						if(i!=index-1) {
							return "false";
						}
					}
				}
			}
			if(targetList.size()>=index) {
				target=(Map<String,String>) targetList.get(index-1);
			}else {
				target=new HashMap<>();
				targetList.add(target);
			}
		}
		//单个目标应用targetMap
		if(StringUtils.isNotBlank(targetId)) {
			target.put("targetId", targetId);
		}
		if(StringUtils.isNotBlank(targetName)) {
			target.put("targetName", targetName);
		}
		target.put("status", "1");
		//将目标文件集合存入map中
		map.put("targetList", targetList);
		//将map再更新存入Session中
		session.setAttribute(key, map);
		return map;
	}
	/**
	 * 删除Session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("deleteSession")
	@ResponseBody
	public Object deleteSession(HttpSession session,String key) {
		Map<String, Object> map = (Map<String, Object>) session.getAttribute(key);
		session.removeAttribute(key);
		return map;
	}
	//移除目标数据
	@SuppressWarnings("unchecked")
	@RequestMapping("removeTargetApp")
	@ResponseBody
	public Object removeTargetApp(HttpSession session,String key,int index) {
		//Session中map
		Map<String, Object> map = (Map<String, Object>) session.getAttribute(key);
		List<Map<String,String>> targetList=new ArrayList<>();
		if(map!=null) {
			targetList =(List<Map<String,String>>) map.get("targetList");
			if(targetList!=null) {
				if(index==1) {
					if(targetList.size()>index) {
						targetList.remove(0);
					}else if(targetList.size()==1){
						targetList= new ArrayList<>();
					}
				}else {
					if(targetList.size()>=index) {
						targetList.remove(index-1);
					}
				}
				map.put("targetList", targetList);
				session.setAttribute(key, map);
			}
	}
		return 0;
	}
	//保存时查看数据是否完整
	@RequestMapping(value="inspect", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings("unchecked")
	public Object inspect(String key,HttpSession session,String topicQueueName) {
		Map<String, Object> map = (Map<String, Object>)session.getAttribute(key);
//		System.out.println("map: " + map);
		if(map==null) {
			return 1;
		}else {
			String ServiceName=(String)map.get("ServiceName");
			if(!StringUtils.isNotBlank(ServiceName)) {
				ServiceName=topicQueueName;
			}
			List<Map<String,String>> targetList =(List<Map<String,String>>) map.get("targetList");
			Map<String,Object> origin =(Map<String,Object>) map.get("origin");
			if(StringUtils.isEmpty(ServiceName)||!Pattern.
					compile("[a-zA-Z0-9\\u4e00-\\u9fa5]").matcher(ServiceName).find()) {
				return 2;
			}else if(origin==null) {
				return 3;
			}else if(targetList==null){
				return 5;
			}
			for(int i=0;i<targetList.size();i++) {
				if(targetList.get(i).size()<5)
					return 6;
			}
		}
		return 0;
	}
	/**
	 * 根据id获取服务配置信息
	 * @param id
	 * @return
	 */
	@RequestMapping(value="queryQueueConfig", method = RequestMethod.POST)
    @ResponseBody
	public Map<String, Object> queryQueueConfig(String id) {
		//服务信息
		Map<String, Object> ServiceConfig = ServiceAccessService.queryById(id);
		return ServiceConfig;
	}
/*	*//**
	 * 修改时校验该主题队列是否发布
	 * @param appName
	 * @param id
	 * @return
	 *//*
	@RequestMapping(method = RequestMethod.POST, value = "/selectByStatus")
	@ResponseBody
	public String selectByStatus(String id) {
		return ServiceAccessService.selectByStatus(id);
	}*/
	/**
	 * 新增时验证应用名称是否重复
	 * @param appName
	 * @param id
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/checkName")
	@ResponseBody
	public String checkAppName(String name,String id) {
		if(Pattern.compile("^[a-zA-Z0-9\\u4e00-\\u9fa5]{1,32}+$").matcher(name).find()) {
			return ServiceAccessService.checkAppName(name,id);
		}else {
			return "false";
		}
	}
	//保存服务接入
	@SuppressWarnings("unchecked")
	@LogAnnotation(argsName="topicQueueName",targetType="主题队列服务接入",methodType="新增")
	@RequestMapping(value= "saveServiceAccess",method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Void> saveServiceAccess(String key,HttpSession session,String topicQueueName) {
		if(session.getAttribute(key)!=null) {
			Map<String, Object> map = (Map<String, Object>)session.getAttribute(key);
			System.out.println("新增服务接入map: " + map);
				if(StringUtils.isEmpty((String)map.get("ServiceName"))) {
					if(StringUtils.isNotBlank(topicQueueName.trim())) {
						map.put("ServiceName", topicQueueName);
					}
				}
			/*if(checkAll(map)==0) {*/
				//新增
				if(checkAll(map)) {
					ServiceAccessService.saveService(map);
					return new ResponseResult<Void>(200,"ok");
				}else {
					return new ResponseResult<>(400 ,"失败");
				}
		}else {
			return new ResponseResult<>(400 ,"失败");
		}
		/*}else {
			return new ResponseResult<>(400, "失败");
		}*/
	}
	//修改服务接入
	@SuppressWarnings("unchecked")
	@LogAnnotation(argsName="topicQueueName",targetType="主题队列服务接入",methodType="修改")
	@RequestMapping(value= "updateServiceAccess",method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Void> UpdateServiceAccess(String key,HttpSession session,String topicQueueName) {
			if(session.getAttribute(key)!=null) {
				Map<String, Object> map = (Map<String, Object>)session.getAttribute(key);
				System.out.println("修改服务接入: " + map);
				if(StringUtils.isEmpty((String)map.get("ServiceName"))) {
					if(StringUtils.isNotBlank(topicQueueName.trim())) {
						map.put("ServiceName", topicQueueName);	
					}
				}
				if(checkAll(map)) {
					if(StringUtils.isNotBlank((String)map.get("id"))) {
						ServiceAccessService.updateService(map);
						return new ResponseResult<>(200, "ok");
					}else {
						return new ResponseResult<>(400 ,"失败");
					}
				}else {
					return new ResponseResult<>(400 ,"失败");
				}
			}else {
				return new ResponseResult<>(400 ,"失败");
			}
			/*System.out.println(checkAll(map));
			if(checkAll(map)==0) {*/
			/*List<Map<String,String>> targetList = new ArrayList<>();
			List<Map<String,String>> histargetList = new ArrayList<>();
			if(map.containsKey("targetList")) {
				targetList = (List<Map<String, String>>) map.get("targetList");
			}
			if(map.containsKey("his_targetList")) {
				histargetList = (List<Map<String, String>>) map.get("his_targetList");
			} 
			boolean status = false;
			for(int i=0;i<targetList.size();i++) {
				for(int m=0;m<histargetList.size();m++) {
					if(targetList.get(i).get("sendType").equals(histargetList.get(m).get("sendType"))&&
							targetList.get(i).get("sendChannel").equals(histargetList.get(m).get("sendChannel"))&&
							  targetList.get(i).get("targetId").equals(histargetList.get(m).get("targetId"))) {
						status = true;
					}
				}
				if(!status) {
					break;
				}
			}
			for(int i=0;i<histargetList.size();i++) {
				for(int m=0;m<targetList.size();m++) {
					if(histargetList.get(i).get("sendType").equals(targetList.get(m).get("sendType"))&&
							histargetList.get(i).get("sendChannel").equals(targetList.get(m).get("sendChannel"))&&
							histargetList.get(i).get("targetId").equals(targetList.get(m).get("targetId"))) {
							status = true;
					}
				}
				if(!status) {
					break;
				}
			}
			if(!status) {*/
				/*ServiceAccessService.updateService(map);
			}
				return new ResponseResult<>(200, "ok");*/
			/*}else {
				return new ResponseResult<>(400, "失败");
			}*/
	}
	@SuppressWarnings("unchecked")
	public static boolean checkAll(Map<String, Object> map) {
		if(map==null) {
			return false;
		}else {
			String ServiceName=(String)map.get("ServiceName");
			List<Map<String,String>> targetList =(List<Map<String,String>>) map.get("targetList");
			Map<String,Object> origin =(Map<String,Object>) map.get("origin");
			if(ServiceName==null||!Pattern.
					compile("[a-zA-Z0-9\\u4e00-\\u9fa5]").matcher(ServiceName).find()) {
				return false;
			}else if(origin==null) {
				return false;
			}else if(targetList==null){
				return false;
			}
			for(int i=0;i<targetList.size();i++) {
				if(targetList.get(i).size()<5) {
					return false;
			}
		}
		return true;
	}
}
	 /**
     * 获取接口返回的结果(POST).
     *
     * @param postUrl          请求接口的url
     * @param requestParam     请求接口的参数
     * @param requestBodyParam 请求接口的Body
     * @param requestHeader    请求接口的Header
     * @return 请求接口的返回值
     * @throws IOException the io exception
     */
	@RequestMapping(value= "setUrl",method = RequestMethod.POST)
	@ResponseBody
    public ResponseResult<Void> getResponseMess(String postUrl, Map<Object, Object> requestParam,Map<Object, Object> requestHeader) {
		try{
			String a  = HttpUtil.sendPost(postUrl.trim(), null);
			if(a!=null && a.contains("responseCode")) {
				return new ResponseResult<Void>(200,"ok");
			}else {
				return new ResponseResult<Void>(400,"失败");
			}
		}catch(Exception e) {
			return new ResponseResult<Void>(400,"失败");
		}
	}
}